<template>
  <view class="reset-page">
    <!-- 返回登录按钮 -->
    <view class="back-home" @tap="handleBack">
      <text class="iconfont icon-back">&#xe697;</text>
      <text class="back-text">返回登录</text>
    </view>
    
    <!-- 重置密码卡片 -->
    <view class="reset-container">
      <view class="reset-card">
        <view class="logo">
          <image class="logo-img" src="../../image/logo.png" mode="aspectFit"></image>
          <text class="logo-text">重置密码</text>
        </view>
        
        <view class="form-group">
          <view class="input-wrapper">
            <text class="iconfont icon-mobile"></text>
            <input 
              class="input" 
              type="number" 
              v-model="phone"
              placeholder="请输入手机号码"
              maxlength="11"
              :class="{ 'error': phoneError }"
              adjust-position="false"
              @focus="onFocus"
              @blur="onBlur"
            />
          </view>
          <text class="error-message" v-if="phoneError">请输入有效的手机号码</text>
        </view>
        
        <view class="form-group">
          <view class="input-wrapper code-wrapper">
            <text class="iconfont icon-safe"></text>
            <input 
              class="input" 
              type="number"
              v-model="code"
              placeholder="请输入验证码"
              maxlength="6"
              :class="{ 'error': codeError }"
              adjust-position="false"
              @focus="onFocus"
              @blur="onBlur"
            />
            <button 
              class="code-btn" 
              :disabled="counting || !phone || phoneError"
              @tap="handleSendCode"
            >{{ codeButtonText }}</button>
          </view>
          <text class="error-message" v-if="codeError">请输入正确的验证码</text>
        </view>
        
        <view class="form-group">
          <view class="input-wrapper">
            <text class="iconfont icon-lock"></text>
            <input 
              class="input" 
              :type="showPassword ? 'text' : 'password'"
              v-model="newPassword"
              placeholder="请设置新密码"
              :class="{ 'error': passwordError }"
              adjust-position="false"
              @focus="onFocus"
              @blur="onBlur"
            />
            <text class="password-toggle" @tap="togglePasswordVisibility">
              <view class="toggle-icon" :class="{ 'active': showPassword }">
                <text class="iconfont" v-if="showPassword">&#xe613;</text>
                <text class="iconfont" v-else>&#xe6c8;</text>
              </view>
            </text>
          </view>
          <text class="error-message" v-if="passwordError">密码长度需要在6-20位之间</text>
        </view>
        
        <view class="reset-btn-area">
          <button class="reset-btn" @tap="handleResetPassword" :disabled="isLoading">确认重置</button>
        </view>
        
        <!-- 底部提示 -->
        <view class="bottom-tips">
          <text class="tips-text">重置密码后，请使用新密码登录</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onUnmounted } from 'vue'
import { resetPassword, sendSms } from '@/api/user'

// 表单数据
const phone = ref('')
const code = ref('')
const newPassword = ref('')
const phoneError = ref(false)
const codeError = ref(false)
const passwordError = ref(false)
const counting = ref(false)
const countdown = ref(60)
const isLoading = ref(false) // 加载状态
const showPassword = ref(false) // 控制密码显示/隐藏
let timer = null

// 验证码按钮文字
const codeButtonText = computed(() => {
  if (counting.value) {
    return `${countdown.value}秒`
  }
  return '获取验证码'
})

// 处理输入框焦点
const onFocus = () => {
  setTimeout(() => {
    uni.pageScrollTo({
      scrollTop: 100,
      duration: 300
    })
  }, 300)
}

const onBlur = () => {
  setTimeout(() => {
    uni.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  }, 300)
}

// 切换密码显示/隐藏
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

// 发送验证码
const handleSendCode = async () => {
  // 验证手机号
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(phone.value)) {
    phoneError.value = true
    uni.showToast({
      title: '请输入有效的手机号码',
      icon: 'none'
    })
    return
  }
  
  // 防止重复点击
  if (counting.value) {
    return
  }
  
  try {
    // 调用发送验证码接口
    await sendSms(phone.value)
    
    // 开始倒计时
    counting.value = true
    countdown.value = 60
    
    // 显示发送成功提示
    uni.showToast({
      title: '验证码已发送',
      icon: 'success',
      duration: 1500
    })
    
    // 开始倒计时
    startCountdown()
  } catch (error) {
    console.error('发送验证码失败', error)
  }
}

// 倒计时函数
const startCountdown = () => {
  // 先清除可能存在的定时器
  clearInterval(timer)
  
  // 设置新的定时器
  timer = setInterval(() => {
    // 减少倒计时
    countdown.value--
    
    // 检查是否结束
    if (countdown.value <= 0) {
      // 清除定时器
      clearInterval(timer)
      timer = null
      // 重置状态
      counting.value = false
      countdown.value = 60
    }
  }, 1000)
}

// 重置密码
const handleResetPassword = () => {
  // 防止重复提交
  if (isLoading.value) return
  
  // 重置错误状态
  phoneError.value = false
  codeError.value = false
  passwordError.value = false
  
  // 验证手机号
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(phone.value)) {
    phoneError.value = true
    return
  }
  
  // 验证验证码
  if (!code.value || code.value.length !== 6) {
    codeError.value = true
    return
  }
  
  // 验证密码
  if (!newPassword.value || newPassword.value.length < 6 || newPassword.value.length > 20) {
    passwordError.value = true
    return
  }
  
  // 显示加载状态
  uni.showLoading({
    title: '重置中...'
  });
  
  isLoading.value = true;
  
  // 调用重置密码接口
  resetPassword({
    phone: phone.value,
    newPassword: newPassword.value,
    code: code.value
  })
    .then(res => {
      uni.showToast({
        title: '重置密码成功',
        icon: 'success'
      });
      
      // 延迟跳转到登录页
      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/login/index'
        });
      }, 1500);
    })
    .catch(err => {
      console.error('重置密码失败:', err);
      uni.showToast({
        title: '重置失败，请重试',
        icon: 'none'
      });
    })
    .finally(() => {
      isLoading.value = false;
      uni.hideLoading();
    });
}

// 返回登录页
const handleBack = () => {
  uni.navigateBack();
}

// 组件销毁时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
})
</script>

<style lang="scss">
page {
  height: 100%;
  background: linear-gradient(135deg, #f0f7f7 0%, #e9f0f5 100%);
}

.reset-page {
  min-height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  box-sizing: border-box;
  
  // 返回登录按钮样式
  .back-home {
    position: fixed;
    top: 40px;
    left: 20px;
    z-index: 100;
    display: flex;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.9);
    padding: 8px 15px;
    border-radius: 20px;
    box-shadow: 0 2px 10px rgba(195, 227, 227, 0.2);
    
    .icon-back {
      font-size: 16px;
      margin-right: 4px;
      color: #2c7873;
    }
    
    .back-text {
      font-size: 14px;
      color: #2c7873;
    }
  }
  
  .reset-container {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    
    .reset-card {
      background: rgba(255, 255, 255, 0.95);
      padding: 30px 25px;
      border-radius: 20px;
      box-shadow: 0 8px 24px rgba(195, 227, 227, 0.2);
      width: 100%;
      max-width: 420px;
      position: relative;
      
      .logo {
        text-align: center;
        margin-bottom: 40px;
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .logo-img {
          width: 60px;
          height: 60px;
          margin-bottom: 12px;
        }
        
        .logo-text {
          color: #2c7873;
          font-size: 22px;
          font-weight: 600;
          line-height: 1.2;
        }
      }
      
      .form-group {
        margin-bottom: 20px;
        
        .label {
          display: block;
          margin-bottom: 8px;
          color: #2c7873;
          font-size: 15px;
          font-weight: 500;
        }
        
        .input-wrapper {
          position: relative;
          background: #fff;
          border-radius: 12px;
          border: 2px solid #c3e3e3;
          overflow: hidden;
          
          .iconfont {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #6FB3B8;
            font-size: 20px;
            z-index: 1;
          }
          
          .password-toggle {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            z-index: 10;
            
            .toggle-icon {
              display: flex;
              justify-content: center;
              align-items: center;
              width: 32px;
              height: 32px;
              border-radius: 50%;
              background-color: rgba(195, 227, 227, 0.05);
              transition: all 0.3s ease;
              
              .iconfont {
                position: static;
                font-size: 18px;
                color: #8d6e63;
                transform: none;
                transition: all 0.3s ease;
              }
              
              &:active {
                background-color: rgba(195, 227, 227, 0.15);
                transform: scale(0.9);
              }
              
              &.active {
                background-color: rgba(195, 227, 227, 0.15);
                
                .iconfont {
                  color: #2c7873;
                }
              }
            }
          }
          
          .input {
            width: 100%;
            height: 48px;
            padding: 0 45px 0 40px;
            font-size: 16px;
            color: #2c7873;
            background: transparent;
            position: relative;
            z-index: 2;
            
            &:focus {
              border-color: #6FB3B8;
              box-shadow: 0 0 0 3px rgba(195, 227, 227, 0.2);
            }
          }
        }
        
        .input-wrapper.code-wrapper {
          padding-right: 110px;
          
          .code-btn {
            position: absolute;
            right: 0;
            top: 0;
            width: 110px;
            height: 48px;
            background: linear-gradient(135deg, #6FB3B8 0%, #2c7873 100%);
            border: none;
            color: white;
            font-size: 14px;
            margin: 0;
            padding: 0;
            line-height: 48px;
            text-align: center;
            border-top-right-radius: 10px;
            border-bottom-right-radius: 10px;
            z-index: 3;
            
            &:disabled {
              opacity: 0.6;
              background: linear-gradient(135deg, #c3e3e3 0%, #6FB3B8 100%);
            }
            
            &:active {
              opacity: 0.9;
            }
          }
        }
        
        .error-message {
          color: #ff5722;
          font-size: 13px;
          margin-top: 6px;
          display: block;
        }
      }
      
      .reset-btn-area {
        margin-bottom: 20px;
      }

      .reset-btn {
        width: 100%;
        height: 48px;
        background: linear-gradient(135deg, #c3e3e3 0%, #2c7873 100%);
        border: none;
        border-radius: 12px;
        color: white;
        font-size: 16px;
        font-weight: 600;
        
        &:active {
          opacity: 0.9;
          transform: translateY(1px);
        }
        
        &:disabled {
          opacity: 0.6;
        }
      }

      .bottom-tips {
        text-align: center;
        margin-top: 15px;
        
        .tips-text {
          font-size: 14px;
          color: #2c7873;
        }
      }
    }
  }
}

// 响应式布局
@media screen and (max-width: 768px) {
  .reset-page {
    padding: 16px;
    
    .reset-container {
      .reset-card {
        padding: 24px 20px;
      }
    }
  }
}
</style> 